package idv.arthur.work;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class QueryRoleList extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public QueryRoleList() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/json");
		response.setCharacterEncoding( wid.UIcodeSet );
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String errPars = "}";
		
		boolean isSU = Boolean.valueOf( request.getParameter("isSU") );
		
		String strSQL = null;
		
		if ( isSU ) {
			strSQL = "SELECT roleId,roleName FROM rolelist ORDER BY roleId ASC";
		} else {
			strSQL = "SELECT roleId,roleName FROM rolelist WHERE roleId<>4  ORDER BY roleId ASC";
		}
		
		ArrayList<InfoStruc> roleLists = new ArrayList<InfoStruc>();

		try {
			conn = wid.getConn(true);
			ps = conn.prepareStatement(strSQL);
			rs = ps.executeQuery();
			while (rs.next()) {
				InfoStruc p = new InfoStruc();
				p.setId(rs.getString("roleId"));
				p.setName( wid.DB2UI( rs.getString("roleName"),conn.getMetaData().getDatabaseProductName() ) );
				roleLists.add(p);
			}
		} catch (SQLException e) {
			wid.kem(conn, ps, e, wid.toEType("SQLException")+errPars, wid.isPrint2Console );
		} catch (UnsupportedEncodingException e) {
			wid.kem(conn, ps, e, wid.toEType("UnsupportedEncodingException")+errPars, wid.isPrint2Console );
		} catch (Exception e) {
			wid.kem(conn, ps, e, wid.toEType("Exception")+errPars, wid.isPrint2Console );
		} finally {
			try {
				if ( rs != null) { rs.close(); }
				if ( ps != null) { ps.close(); }
				if ( conn != null) { conn.close(); }	
			} catch (SQLException e ) {
				System.out.println(wid.errProcess(e));
			}
		}

		response.getWriter().write( new Gson().toJson( roleLists ) );
	}
}